package com.is2.patchinglife.listener;

import com.is2.patchinglife.manager.LocalDataManager;
import com.is2.patchinglife.manager.NotificationHandler;
import com.is2.patchinglife.util.SensorValues;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.telephony.TelephonyManager;

public class ProximityListener implements SensorEventListener{
		
		// CONSTANTS
		private	final long NORM = 1000000000; 	// 1s [ns]
		
		// FREQUENCY PARAMETERS
	    private double lastAcquire;				// time of last acquired value
	    private double minDelay = 0.5; 			// delay [s]
	
	    // prox_01
	    private double startProx01 = -1;		// trophy start time
		private String proxKey01 = "prox_01";
		private int TIMEOUT = 15;				// timeout [s]
		private double OFF = 0.5;				// value offset
	     
		@Override
		/** Activated when sensor accuracy changes **/
		public void onAccuracyChanged(Sensor arg0, int arg1){}
	
		@Override
		/** Activated when sensor value changes **/
		public void onSensorChanged(SensorEvent event){
			
			// update sensor value in SHARED_MEMORY
			SensorValues.setValue("prox",event.values[0]);
			
			// slow down execution frequency
			if((lastAcquire+minDelay)<(event.timestamp/NORM)){
				lastAcquire = event.timestamp/NORM;
				
				// trophy codes
				prox_01(event.values[0]);
			}
		}
		
		// TROPHY: prox_01
		private void prox_01(double _val){
	
			if(!LocalDataManager.getGotIT(proxKey01) &&
				LocalDataManager.getInhibited("telephony")){	// needed by sensor inhibition
				
				if(startProx01>0 && (lastAcquire-startProx01)>=TIMEOUT){
					LocalDataManager.gotNewTrophy(proxKey01);
					NotificationHandler.displayNotificationMessage(LocalDataManager.getName(proxKey01),LocalDataManager.getDesc(proxKey01),LocalDataManager.getID(proxKey01));
				}
				
				if(SensorValues.getValue("NEWtel")==(double)TelephonyManager.CALL_STATE_OFFHOOK){
					if(_val<OFF && startProx01==-1)
						startProx01=lastAcquire;
					else if(_val>=OFF)
						startProx01=-1;
				}else{
					startProx01=-1;
				}
			}
		}	
}